<?php


namespace app\user\controller;


use think\Db;
use think\Loader;

class Finance extends Base
{
    public function FinanceList(){
        //条件查询
        $Data = Param();

        $this->assign('Data',$Data);
        $Where = [];

        $Where['user_id'] = $this->user_id;
        //总记录条数
        $Count = Db::name('finance')->where($Where)->count();
        $this->assign('Count', $Count);

        //佣金信息
        $List = Db::name('finance')->where($Where)->order('id desc')->paginate(10,false);
        $FinanceList = $List->toArray()['data'];
        foreach ($FinanceList as $k=>$v){
            $from = UserInfo(['id'=>$v['from_id']]);
            $FinanceList[$k]['from_name'] = $from['username'];
        }
        $this->assign('FinanceList', $FinanceList);

        //分页
        $this->assign('Page', $List->render());

        return $this->fetch('FinanceList');
    }

    public function FinanceExport(){

        //条件查询
        $Data = Param();
        $Where = [];
        if (empty($Data)){
            $Data = [
                'reward_type' => 0,
                'begin_time' => '',
                'end_time' => '',
            ];

        }
        $this->assign('Data',$Data);

        //等级查询
        if($Data['reward_type'] > 0){
            $Where['reward_type'] = $Data['reward_type'];
        }


        //时间查询
        if($Data['begin_time'] != '' && $Data['end_time'] == ''){   //只有开始时间没有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $Where['add_time'] = array('egt',$BeginTime );
        }

        if($Data['begin_time'] == '' && $Data['end_time'] != ''){   //只有结束时间没有开始时间
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array('elt',$EndTime );
        }

        if($Data['begin_time'] != '' && $Data['end_time'] != ''){   //有开始时间有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array(array('egt',$BeginTime ),array('elt',$EndTime ));
        }

        $Where['user_id'] = $this->user_id;
        $xlsData = Db('finance')->where($Where)->select();

        Loader::import('PHPExcel.PHPExcel');
        Loader::import('PHPExcel.PHPExcel.Worksheet.Drawing');
        Loader::import('PHPExcel.PHPExcel.Writer.Excel2007');
        $objExcel = new \PHPExcel();
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');

        $objActSheet = $objExcel->getActiveSheet();
        $key = ord("A");
        $letter =explode(',',"A,B,C,D,E");
        $arrHeader = array('会员账号','来源账号','佣金数量','佣金类型','记录时间');

        //填充表头信息
        $lenth =  count($arrHeader);
        for($i = 0;$i < $lenth;$i++) {
            $objActSheet->setCellValue("$letter[$i]1","$arrHeader[$i]");
        };


        //填充表格信息
        foreach($xlsData as $k=>$v){
            $UserInfo = UserInfo(['id'=>$xlsData[$k]['user_id']]);
            $FromInfo = UserInfo(['id'=>$xlsData[$k]['from_id']]);

            $k +=2;
            $objActSheet->setCellValue('A'.$k, $UserInfo['username']." ");
            $objActSheet->setCellValue('B'.$k, $FromInfo['username']." ");
            $objActSheet->setCellValue('C'.$k, $v['num']);
            $objActSheet->setCellValue('D'.$k, $v['remarks']);
            $objActSheet->setCellValue('E'.$k, date('Y-m-d H:i',$v['add_time']));
            // 表格高度
            $objActSheet->getRowDimension($k)->setRowHeight(20);

            $width = array(10,15,20,25,30);
            //设置表格的宽度
            $objActSheet->getColumnDimension('A')->setWidth($width[1]);
            $objActSheet->getColumnDimension('B')->setWidth($width[1]);
            $objActSheet->getColumnDimension('C')->setWidth($width[1]);
            $objActSheet->getColumnDimension('D')->setWidth($width[2]);
            $objActSheet->getColumnDimension('E')->setWidth($width[2]);
        }


        $outfile = "佣金明细列表.xlsx";
        ob_end_clean();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$outfile.'"');
        header("Content-Transfer-Encoding: binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");

        $objWriter->save('php://output');
    }

    /**
     * Notes:投资
     * Time: 2022/1/14  11:39
     * User: Qian
     * @return mixed
     */
    public function Deposit(){
        $UserInfo = UserInfo(['id'=>$this->user_id]);
        $Config = Config();
        if (IsPost()){
            $Data = Param();
            //检查是否投资过
//            $check = Db::name('user_deposit')->where(['user_id'=>$UserInfo['id'],'status'=>['in',[0,1,2]]])->find();
//            if ($check){
//                return  ['status'=>0,'message'=>'已投资过'];
//            }
            if ($Data['amount'] == '' || $Data['amount'] <= 0 || !is_numeric($Data['amount'])){
                return  ['status'=>0,'message'=>'投资数量格式错误'];
            }
            if(!preg_match('/^([1-9][0-9]*){1,10}$/',$Data['amount']))
            {
                return  ['status'=>0,'message'=>'投资数量必须为整数'];
            }
            if ($Data['amount']%100 != 0){
                return  ['status'=>0,'message'=>'投资数量须为100整数倍'];
            }
            if ($Data['amount'] < 1000){
                return  ['status'=>0,'message'=>'1000U起投'];
            }
//            if ($Data['amount'] > $UserInfo['balance_1']){
//                return  ['status'=>0,'message'=>'账户余额不足'];
//            }
            if (md5($Data['password']) != $UserInfo['password_login']){
                return  ['status'=>0,'message'=>'密码错误'];
            }
            if ($Data['img'] == ''){
                return  ['status'=>0,'message'=>'请上传支付凭证'];
            }
            if ($Data['pay_type'] == 1){
                $address = $Config['usdt_address'];
            }elseif ($Data['pay_type'] == 2){
                $address = $Config['usdt_address_trc'];
            }elseif ($Data['pay_type'] == 3){
                $address = $Config['usdt_address_erc'];
            }else{
                return  ['status'=>0,'message'=>'充值方式错误'];
            }
            $usersave['balance_1'] = $UserInfo['balance_1'] - $Data['amount'];
            $usersave['achievement'] = $UserInfo['achievement'] + $Data['amount'];
            Db::startTrans();
            try {
                $add['user_id'] = $UserInfo['id'];
                $add['order_id'] = date('YmdHis').rand(10000,99999);
                $add['amount'] = $Data['amount'];
                $add['total_day'] = 365;
                $add['pay_type'] = $Data['pay_type'];
                $add['recharge_address'] = $address;
                $add['img'] = $Data['img'];
                $add['add_time'] = time();
                $add['status'] = 0; //待审核
                $id = Db::name('user_deposit')->insertGetId($add);
//                Db::name('user')->where(['id'=>$UserInfo['id']])->update($usersave);
//                FinanceAdd($UserInfo['id'],$UserInfo['id'],$Data['amount'],1,10,'投资','','',$id);
//                //增加团队业绩
//                Db::query("call add_recommend_achievement(:id,:amount)",['id'=>$UserInfo['id'],'amount'=>$Data['amount']]);
//                //升级
//                Db::query("call user_uplevel(:user_id)",['user_id'=>$UserInfo['id']]);
                Db::commit();
                return  ['status'=>1,'message'=>'投资提交成功,','url'=>url("Index/Index")];
            }catch (\Exception $e){
                Db::rollback();
                return  ['status'=>0,'message'=>'投资失败'];
            }

        }
        $record = Db::name('user_deposit')->where(['user_id'=>$UserInfo['id']])->find();
        $this->assign('UserInfo',$UserInfo);
        $this->assign('record',$record);
        $address1 = Db::name('system_address')->where(['type'=>1])->select();
        $address2 = Db::name('system_address')->where(['type'=>2])->select();
        $address3 = Db::name('system_address')->where(['type'=>3])->select();
        $this->assign('address1',json_encode($address1,true));
        $this->assign('address2',json_encode($address2,true));
        $this->assign('address3',json_encode($address3,true));
        return $this->fetch('Deposit');
    }
}